package www.com.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET_KEY = "daniuzi";
    private static final Long expTime = Long.valueOf(1000 * 60 * 60 * 5);

    //生成密钥
    public static String createJwt(String name) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("name", name);
        // claims.put("exp", System.currentTimeMillis() + 1000 * 60 * 60 * 10); // 设置过期时间，例如10小时
        String jwt = Jwts.builder()
                .setSubject("name")
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expTime))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
        return jwt;
    }
   public  static  Boolean validateJwt(String token) {
       Jws<Claims> claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
       // 获取 JWT 的签名
       String originalSignature = claims.getSignature();
       // 重新生成签名
       String newSignature = Jwts.builder()
               .setClaims(claims.getBody())
               .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
               .compact().split("\\.")[2];
       return originalSignature.equals(newSignature);
   }
}
